package com.ropeok.Result;


import com.ropeok.constant.ResultConstant;

/**
 * 接口统一返回包装类,所有接口返回Result对象
 */
//包装类,和前端约定什么时后成功什么时候失败,因为后端(controller)有各种各样的返回值

public class Result<T> {
    //判断是否请求失败,和前端约定参数
    private boolean success;
    private Integer code;
    //请求失败后的原因是
    private String msg;
    //后台所需要携带的数据
    private  T data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


    public Result() {
        this.code=200;
        this.msg="成功";
    }

    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 返回一个成功信息的方法,无数据的成功
     * @param msg
     * @return
     * @param <T>
     */
    public static <T> Result<T>success(String msg){
        Result<T> result=new Result<>();
        result.setMsg(msg);
        result.setCode(ResultConstant.SUCCESS);
        return result;
    }

    /**
     * 无数据返回成功
     */
    public  static <T> Result<T> success(){
        return new Result(ResultConstant.SUCCESS,"成功",null);
    }

    /**
     * 有数据的成功
     * @param data
     * @return
     * @param <T>
     */
    public static <T> Result<T> success(T data){
        return new Result(ResultConstant.SUCCESS,"成功",data);
    }

    /**
     * 返回错误信息
     * @param msg
     * @return
     * @param <T>
     */
    public static <T> Result<T> error(String msg){
        Result<T> result=new Result<>();
        result.setCode(ResultConstant.ERROR);
        result.setMsg(msg);
        return result;
    }

    /**
     * 请求错误,自己可设置的code,设定是何种错误,Service自定义异常
     * @param code
     * @param msg
     * @return
     * @param <T>
     */
    public  static <T> Result<T> error(Integer code,String msg){
        Result<T> result=new Result<>();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}
